package org.idea.spring.ioc.javabeans;

import org.idea.spring.ioc.bean.Person;

import java.beans.*;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

/**
 * 通过原始的javabeans技术来实现ioc的注入
 *
 * @Author idea
 * @Date created in 9:59 下午 2020/4/22
 */
public class MapToBeanUtil {

    /**
     * 进行转换
     */
    public static Person convert(Map<String, String> parameters) throws Exception {
        //注册bean的编辑器,放到一个WeakHashMap中
        PropertyEditorManager.registerEditor(Person.class, PersonEditor.class);
        Person person = new Person();
        BeanInfo beanInfo = Introspector.getBeanInfo(Person.class, Object.class);
        //获取所有的属性
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        Stream.of(pds).forEach(propertyDescriptor -> {
            System.out.println(propertyDescriptor);
            Class<?> propertyClass = propertyDescriptor.getPropertyType();
            Method writeMethod = propertyDescriptor.getWriteMethod();
            PropertyEditor editor = PropertyEditorManager.findEditor(propertyClass);
            propertyDescriptor.setPropertyEditorClass(PersonEditor.class);
            if (propertyClass == Integer.class && editor != null) {
                //根据类型查找注册器
                editor.setAsText(parameters.get(propertyDescriptor.getName()));
            } else if (propertyClass == String.class) {
                editor.setAsText(parameters.get(propertyDescriptor.getName()));
            }
            try {
                writeMethod.invoke(person, editor.getValue());
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
        return person;
    }

    static class PersonEditor extends PropertyEditorSupport {

        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            Integer val = Integer.valueOf(text);
            setValue(val);
        }
    }

    public static void main(String[] args) throws Exception {
        Map<String, String> paramMap = new HashMap<>(2);
        paramMap.put("age", "11");
        paramMap.put("name", "idea");
        Person person = convert(paramMap);
        System.out.println(person.toString());
    }

}
